package logic

import (
	"api/pkg"
	"context"
	"github.com/google/uuid"
	"goods_srv/goods"
	"order_srv/order"
	"strconv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 新增订单

	//模拟登录
	userid := 1

	//判断商品是否存在
	detail, err := l.svcCtx.GoodsSrv.GoodsDetail(l.ctx, &goods.GoodsDetailRequest{GoodsId: req.GoodsId})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}
	if detail.GoodsId == 0 {
		return &types.RegMsgResponse{
			Cre:  -2,
			Msg:  "商品不存在,无法购买",
			Data: nil,
		}, err
	}
	//判断商品库存
	stock, _ := l.svcCtx.GoodsSrv.GetGoodsStock(l.ctx, &goods.GetGoodsStockRequest{GoodsId: req.GoodsId})
	if stock.GoodsStock < req.Num {
		return &types.RegMsgResponse{
			Cre:  -4,
			Msg:  "商品库存不足,无法购买",
			Data: nil,
		}, err
	}

	//生成订单号
	sn := uuid.NewString()

	//计算总价
	sum := detail.GoodsPrice * float32(req.Num)

	//新增订单
	_, err = l.svcCtx.OrderSrv.CreateOrder(l.ctx, &order.CreateOrderRequest{
		UserId:  int64(userid),
		GoodsSn: sn,
		Amount:  sum,
		Payment: 1,
		Status:  1,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -3,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	//删除库存
	_, err = l.svcCtx.GoodsSrv.DelGoodsStock(l.ctx, &goods.DelGoodsStockRequest{
		GoodsId: req.GoodsId,
		Num:     req.Num,
	})

	//订单转字符串
	amount := strconv.FormatFloat(float64(sum), 'f', -1, 32)

	//调用支付接口
	zfUrl := pkg.Alipay(sn, amount)

	return &types.RegMsgResponse{
		Cre: 0,
		Msg: "新增订单成功",
		Data: map[string]interface{}{
			"Url": zfUrl,
		},
	}, err
}
